package znet

import (
	"bytes"
	"encoding/binary"
	"errors"
	"zinx/utils"
	"zinx/ziface"
)

type DataPack struct {
}

func NewDataPack() *DataPack {
	return &DataPack{}
}

// GetHeadLen 获取包的长度(单位字节)
func (dp *DataPack) GetHeadLen() uint32 {
	// DataLen uint32(4字节) + ID uint32(4字节)
	return 8
}

// Pack 封包方法
func (dp *DataPack) Pack(msg ziface.IMessage) ([]byte, error) {
	// 创建一个存放bytes字节的缓冲
	buffer := bytes.NewBuffer([]byte{})

	// 依次将dataLen、MsgId、data写进buffer中
	err := binary.Write(buffer, binary.LittleEndian, msg.GetMsgLen())
	if err != nil {
		return nil, err
	}

	err = binary.Write(buffer, binary.LittleEndian, msg.GetMsgId())
	if err != nil {
		return nil, err
	}

	err = binary.Write(buffer, binary.LittleEndian, msg.GetData())
	if err != nil {
		return nil, err
	}

	return buffer.Bytes(), nil
}

// Unpack 拆包方法
func (dp *DataPack) Unpack(data []byte) (ziface.IMessage, error) {
	// 创建一个从输入二进制数据的ioReader
	dataBuffer := bytes.NewReader(data)

	// 只解压Head信息，得到dataLen和MsgID
	msg := &Message{}
	err := binary.Read(dataBuffer, binary.LittleEndian, &msg.DataLen)
	if err != nil {
		return nil, err
	}

	err = binary.Read(dataBuffer, binary.LittleEndian, &msg.Id)
	if err != nil {
		return nil, err
	}

	// 判断dataLen是否已经超出了允许得分最大包长度
	if utils.GlobalObject.MaxPackageSize > 0 && msg.DataLen > utils.GlobalObject.MaxPackageSize {
		return nil, errors.New("too large msg data")
	}

	return msg, nil
}
